package com.hz.friends.activity;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVUser;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.hz.friends.activity.UserInfosActivity.MessageAdpter;
import com.hz.friends.application.CustomApplication;
import com.hz.friends.serverrequest.ALUserEngine;
import com.hz.friends.serverrequest.ALEngineConfig.CallBack;
import com.hz.friends.utils.BitmapUtils;
import com.hz.friends.utils.DensityUtil;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

public class SubMessageActivity extends BaseActivity {
	private PullToRefreshListView mlistview;
	private final int limit = 20;// 分页
	private int skip = 0;// 跳过记录条数
	private AVUser user = null;
	private AQuery aq;
	private MyAdpter adpter;
	private FrameLayout layout_levelmsg;
	private LinearLayout layout_tips;
	private LinearLayout includebar;
	private TextView txv_nodata;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_submessage);
		init();
		initViews();
		uploadMessages();
	}

	@Override
	protected void init() {
		user = ((CustomApplication) getApplication()).user;
		aq = new AQuery(this);

	}

	@Override
	protected void initViews() {

		ImageButton imbtn_bar_left = (ImageButton) findViewById(R.id.imbtn_bar_left);
		ImageButton imbtn_bar_right = (ImageButton) findViewById(R.id.imbtn_bar_right);
		TextView imbtn_bar_title = (TextView) findViewById(R.id.imbtn_bar_title);
		imbtn_bar_right.setVisibility(View.INVISIBLE);
		imbtn_bar_left.setImageResource(R.drawable.ic_leftback_arrow);
		imbtn_bar_title.setText("Message");
		imbtn_bar_left.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		});
		mlistview = (PullToRefreshListView) findViewById(R.id.mlistview);
		layout_tips = (LinearLayout) findViewById(R.id.layout_tips);
		includebar = (LinearLayout) findViewById(R.id.includebar);
		
        final ImageView imv_topheard = (ImageView)findViewById(R.id.imv_topheard);
        TextView txv_topname = (TextView)findViewById(R.id.txv_topname);
         txv_nodata = (TextView)findViewById(R.id.txv_nodata);
        
		adpter = new MyAdpter(SubMessageActivity.this,
				new ArrayList<AVObject>());
		mlistview.setAdapter(adpter);
		
		String heardurl = user.getString("headViewURL");
		String nickname = user.getString("nickname");
		txv_topname.setText(nickname);
		
		final int width = DensityUtil.dip2px(getApplicationContext(), 43);
		final int stroke = DensityUtil.dip2px(getApplicationContext(), 1);
		Bitmap crclebitmap = BitmapUtils.drawCycleImage("#c4c4c5", width);
		Bitmap crclestrokebitmap = BitmapUtils.getCircleStrokbitmap(
				getApplicationContext(), crclebitmap, width, stroke, "#eeeeee");
		imv_topheard.setImageBitmap(crclestrokebitmap);

		aq.ajax(heardurl, Bitmap.class, new AjaxCallback<Bitmap>() {
			@Override
			public void callback(String url, Bitmap bitmap,
					AjaxStatus status) {
				Bitmap mbitmap = BitmapUtils.getCircleStrokbitmap(getApplicationContext(),
						bitmap, width, stroke, "#eeeeee");
				imv_topheard.setImageBitmap(mbitmap);
			}
		});
		
		
		layout_levelmsg = (FrameLayout) findViewById(R.id.layout_levelmsg);
		ImageButton imbtn_botomback = (ImageButton) findViewById(R.id.imbtn_botomback);
		imbtn_botomback.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		});
		Button btn_message = (Button) findViewById(R.id.btn_message);
		Button btn_present = (Button) findViewById(R.id.btn_present);
		btn_message.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				startActivity(LevelMessageActivity.class);
			}
		});

		btn_present.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				startActivity(SendGiftActivity.class);
			}
		});
		
		int pageflag = getIntent().getIntExtra("pageflag", 0);
		if (pageflag == 1) {
			layout_levelmsg.setVisibility(View.VISIBLE);
			layout_tips.setVisibility(View.VISIBLE);
			includebar.setVisibility(View.GONE);
		} else {
			layout_levelmsg.setVisibility(View.GONE);
			layout_tips.setVisibility(View.GONE);
			includebar.setVisibility(View.VISIBLE);
		}
		AVUser curruser = AVUser.getCurrentUser();
		if (curruser.getObjectId().equals(user.getObjectId())) {// 自己
			btn_message.setVisibility(View.GONE);
			btn_present.setVisibility(View.GONE);
		}
	}

	@Override
	protected void setViews() {

	}

	@Override
	protected void initEvents() {
		mlistview.setOnRefreshListener(new OnRefreshListener2<ListView>() {

			@Override
			public void onPullUpToRefresh(
					PullToRefreshBase<ListView> refreshView) {
				uploadMessages();
			}

			@Override
			public void onPullDownToRefresh(
					PullToRefreshBase<ListView> refreshView) {
				adpter.clearData();
				skip = 0;
				uploadMessages();
			}
		});
	}

	private void uploadMessages() {
		ALUserEngine.defauleEngine().getMessageOfBBSList(user, limit, skip,true,
				new CallBack() {

					@Override
					public void done(Object object, AVException avexception) {
						mlistview.onRefreshComplete();
						txv_nodata.setVisibility(View.GONE);
						if (avexception == null) {
							List<AVObject> list = (List<AVObject>) object;

							if (list == null || list.size() == 0) {
								if (adpter.getCount() == 0) {
//									showSysToast("没有消息");
									txv_nodata.setVisibility(View.VISIBLE);
									mlistview.setVisibility(View.GONE);
								} else
									showSysToast("没有更多");
							} else {
								skip = skip + list.size();
								adpter.addData(list);
								adpter.notifyDataSetChanged();
							}
						} else {
							avexception.printStackTrace();
							showSysToast("请求错误");

						}
					}
				});
	}

	class MyAdpter extends BaseAdapter {
		private List<AVObject> list = null;
		private Context context;

		public MyAdpter(Context context, List<AVObject> list) {
			this.list = list;
			this.context = context;
		}

		@Override
		public int getCount() {
			return list.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		public void clearData() {
			this.list.clear();
		}

		public void addData(List<AVObject> list) {
			if (list == null)
				return;
			this.list.addAll(list);

		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View view = LayoutInflater.from(SubMessageActivity.this).inflate(
					R.layout.adpter_submessage, null);
			final ImageView imv_heard = (ImageView) view
					.findViewById(R.id.imv_heard);
			TextView txv_name = (TextView) view.findViewById(R.id.txv_name);
			LinearLayout layout_sex = (LinearLayout) view.findViewById(R.id.layout_sex);
			ImageView imv_sex = (ImageView) view.findViewById(R.id.imv_sex);
			TextView txv_age = (TextView) view.findViewById(R.id.txv_age);
			TextView txv_clock = (TextView) view.findViewById(R.id.txv_clock);
			TextView txv_content = (TextView) view.findViewById(R.id.txv_content);
			LinearLayout layout_gift = (LinearLayout) view.findViewById(R.id.layout_gift);
			ImageView imv_gift = (ImageView) view.findViewById(R.id.imv_gift);
			TextView txv_giftnum = (TextView) view.findViewById(R.id.txv_giftnum);
			
			
			AVObject obj = list.get(position);
			AVUser fromuser = obj.getAVUser("fromUser");
			String message = obj.getString("text");
			Date create = obj.getCreatedAt();
			String nickname = fromuser.getString("nickname");
			int age = fromuser.getInt("age");
			int gender = fromuser.getInt("gender");
			String imageurl = fromuser.getString("headViewURL");
			AVObject giftRecorder = obj.getAVObject("giftRecorder");

			txv_name.setText(nickname);
			txv_content.setText(message);
			setGiftTime(txv_clock, create);
			txv_age.setText(String.valueOf(age));

		
			
			final int width = DensityUtil.dip2px(context, 70);
			Bitmap crclebitmap = BitmapUtils.drawCycleImage("#c4c4c5", width);
			Bitmap crclestrokebitmap = BitmapUtils.getCircleStrokbitmap(
					context, crclebitmap, width, 1, "#eeeeee");
			imv_heard.setImageBitmap(crclestrokebitmap);
			// final int stroke = DensityUtil.dip2px(context, 1);
			aq.ajax(imageurl, Bitmap.class, new AjaxCallback<Bitmap>() {
				@Override
				public void callback(String url, Bitmap bitmap,
						AjaxStatus status) {
					Bitmap mbitmap = BitmapUtils.getCircleStrokbitmap(context,
							bitmap, width, 1, "#b1d5aa");
					imv_heard.setImageBitmap(mbitmap);
				}
			});
			
			if(gender == 1){//女
				layout_sex.setBackgroundResource(R.drawable.shape_bj_icwoman_xml);
				imv_sex.setImageResource(R.drawable.ic_woman);
			}else{//男
				layout_sex.setBackgroundResource(R.drawable.shape_bj_icman_xml);
				imv_sex.setImageResource(R.drawable.ic_man);
			}
			
			//礼物显示
			if(giftRecorder != null){
				AVObject gift = giftRecorder.getAVObject("gift");
				if(gift != null){
					int giftnum = giftRecorder.getInt("number");
					String gifturl = gift.getString("imageURL");
					aq.id(imv_gift).image(gifturl, true, true);
					txv_giftnum.setText("x"+String.valueOf(giftnum));
					layout_gift.setVisibility(View.VISIBLE);
				}
			
			}

			return view;
		}

		private void setGiftTime(TextView txv, Date date) {
			Date currdate = new Date();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			if (sdf.format(currdate).equals(sdf.format(date))) {// 同一天
				int hour = currdate.getHours() - date.getHours();
				if (hour == 0) {
					int min = currdate.getMinutes() - date.getMinutes();
					txv.setText(min + " mins ago");
				} else {
					txv.setText(hour + " hours ago");
				}
			} else {
				txv.setText(sdf.format(date));
			}
		}
	}
}
